#!/usr/bin/env bash

workspace='/opt/sea-archiver'
service_name="sea-archiver"
apt_packages="smartmontools"
pip_packages="falcon uvicorn hupper pycryptodome pyopenssl pyjwt aiofiles jinja2 psutil pySMART"
service_path="/usr/lib/systemd/system/$service_name.service"

#######################################
# pre clear
echo "[Info]Cleaning old file (service, venv)"
rm -rf "${workspace}/venv"
rm -rf "${service_path}"
#rm -rf "/usr/lib/systemd/system/sea_archiver.service"
systemctl disable $service_name

#######################################
# install and create venv
echo "[Info]Update apt"
wait_apt1=$(apt update)

echo "[Info]Installing required packages..."
wait_apt2=$(apt install -y ${apt_packages})

echo "[Info]Installing python venv..."
wait_apt2=$(apt install -y python3.11-venv)

echo "[Info]Creating virtual env..."
wait_apt3=$(python3 -m venv "$PWD"/venv)

echo "[Info]Activing venv..."
. "$PWD"/venv/bin/activate

#######################################
# install pip package
echo "[Info]Install pip packages: ${pip_packages}"
echo "[Tips](It may take a long time without any prompts or displays before installation is complete or errors occur)..."
wait_pip1=$(eval "pip install ${pip_packages}")

#######################################
# run python preflight script
echo "[Info]Runing preflight python script at $PWD/App_preflight.py..."
wait_py1=$(eval "$PWD/venv/bin/python3 App_preflight.py --service_name $service_name")

#######################################
# create service soft link
echo "[Info]Creating service file softlink..."
ln "./service/${service_name}.service" "${service_path}"
wait_sys1=$(systemctl daemon-reload)
echo "[Info]Automatic part finished!"

#######################################
echo "-----------------------------------------------------------"
echo "[Warn]please open firewall port manually:"
echo "[eg] firewall-cmd --zone=public --add-port=12100/tcp --permanent"
echo "[eg] ufw allow 12100/tcp"
echo "[eg] iptables -A INPUT -p tcp --dport 12100 -j ACCEPT"
echo "-----------------------------------------------------------"
echo "[Tips]Python venv had been activated, run pip in this shell will install to venv folder."
echo "[Tips]you may need run [apt-get install db-util libpam-pwdfile] to handle vsftpd virtual user."
echo "[Tips]Test the app: [./venv/bin/python3 ./App_SeaArchiver.py]"
echo "[Tips]Start the APP: [systemctl start $service_name]"
echo "[Info]Script execute finished."